package com.mjlf.mongo;


import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ClassName MongoDbJDBC
 * @auther mjlf
 * @Date 2019/6/12 14:57
 * @Description mongoDb jdbc连接
 */
public class MongoDbJDBC  {

    public static void main(String[] args){

        try {
            MongoClient client = new MongoClient("192.168.1.4", 32769);
            MongoDatabase mongoDatabase = client.getDatabase("test");
            System.out.println(mongoDatabase.getName());


            //安全认证方式：
            ServerAddress serverAddress = new ServerAddress("192.168.1.4", 32769);
            List<ServerAddress> addresses = new ArrayList<>();
            addresses.add(serverAddress);

            MongoCredential mongoCredential = MongoCredential.createCredential("test", "test_db", "test".toCharArray());

            MongoClient mongoClient = new MongoClient(addresses, mongoCredential, MongoClientOptions.builder().build());

            MongoDatabase database = mongoClient.getDatabase("test_db");
            System.out.println(database.getCollection("user").find().first());

            //创建集合
//            database.createCollection("col");

            //获取集合名称
            Iterator iterator = database.listCollectionNames().iterator();
            while (iterator.hasNext()){
                System.out.println(iterator.next());
            }

            //获取集合中的文档
            MongoCollection<Document> mongoCollection = database.getCollection("user");
            FindIterable<Document> documents = mongoCollection.find();
            System.out.println(documents.first());

            //添加文档
            Document document = new Document();
            document.append("title", "插入数据");
            document.append("name", "不知道名称");
            mongoCollection.insertOne(document);


            //更新文档
            mongoCollection.updateMany(Filters.eq("title", "插入数据"),
                    new Document("$set", new Document("title", "数据")));

            //删除数据
            mongoCollection.deleteMany(Filters.eq("title", "数据"));

            mongoClient.close();
            client.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
